package impl

import (
	"context"

	"gitee.com/liuxiaowei123/vblog-1.1/app/user"
	"gitee.com/liuxiaowei123/vblog-1.1/config"
	"gitee.com/liuxiaowei123/vblog-1.1/exception"
	"gitee.com/liuxiaowei123/vblog-1.1/ioc"
	"gorm.io/gorm"
)

const AppName = "UserController"

var _ user.UserService = &UserServiceImpl{}

func init() {
	ioc.IocController().Registry(&UserServiceImpl{})
}

type UserServiceImpl struct {
	db *gorm.DB
}

func (u *UserServiceImpl) Init() {
	u.db = config.C.Mysql.Getconn().Debug()
}

func (u *UserServiceImpl) Name() string {
	return AppName
}

// func NewUserServiceImpl() *UserServiceImpl {
// 	return &UserServiceImpl{
// 		db: config.C.Mysql.Getconn().Debug(),
// 	}
// }

//连接数据库

func (u *UserServiceImpl) CreaterUser(c context.Context, req *user.CreaterUserRequest) (*user.User, error) {
	// 1.校验
	if req.UserName == "" || req.Password == "" {
		panic("请输入用户名或密码")
	}

	// 2.创建用户
	ins := user.NewUser(req)

	// 3.保存用户
	// 连接数据库：dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	// db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	// db.Create(ins)
	err := u.db.WithContext(c).Create(ins).Error
	if err != nil {
		return nil, err
	}

	// 4.返回用户
	return ins, nil
}

func (u *UserServiceImpl) DeleterUser(c context.Context, req *user.DeleterUserRequest) error {
	d := user.NewDescribeUserRequestById(req.Idstring())
	ins, err := u.DescribeUser(c, d)
	if err != nil {
		panic(err)
	}
	err = u.db.WithContext(c).Delete(ins).Error
	if err != nil {
		panic(err)
	}
	return nil
}

func (u *UserServiceImpl) DescribeUser(c context.Context, req *user.DescribeUserRequest) (*user.User, error) {
	query := u.db.WithContext(c)
	ins := user.NewUser(user.NewCreaterUserRequest())

	switch req.DescribeBy {
	case user.DESCRIBEBy_ID:
		query = query.Where("id = ?", req.DescribeByValue)
	case user.DESCRIBEBy_USERNAME:
		query = query.Where("user_name = ?", req.DescribeByValue)
	}
	err := query.First(ins).Error
	if err != nil {
		return nil, exception.NewNotfound("用户：%s没有查到", req.DescribeByValue)
	}

	return ins, nil
}
